package com.jinlejia.erp.ui.mine.transfer;

import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.freedom.yefeng.yfrecyclerview.YfLoadMoreListener;
import com.jinlejia.erp.R;
import com.jinlejia.erp.adapter.TransferAuditAdapter;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.databinding.ActivityTransferAuditListBinding;
import com.jinlejia.erp.ui.mine.adapter.GirdDropDownAdapter;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jzxiang.pickerview.TimePickerDialog;
import com.jzxiang.pickerview.data.Type;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;

public class TransferAuditListActivity extends AppCompatActivity implements YfLoadMoreListener, SwipeRefreshLayout.OnRefreshListener {

    private String[] headers = {"未进行审核", "审核状态", "异动时间"};
    private String[] isCheck = {"未进行审核", "已完成审核"};
    private String[] checkState = {"不限", "待审核", "审核不通过", "审核通过"};
    private List<View> popupViews = new ArrayList<>();
    private GirdDropDownAdapter checkAdapter;
    private GirdDropDownAdapter stateAdapter;

    TransferAuditAdapter adapter;
    JSONObject jsonObject = new JSONObject();

    int pageIndex = 1;
    private boolean mLoadingLock = false;

    private ActivityTransferAuditListBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_transfer_audit_list);
        binding.backBtn.setOnClickListener(view -> finish());
        binding.refresh.setColorSchemeResources(R.color.yellow, R.color.light_yellow);
        binding.refresh.setOnRefreshListener(this);

        //init state menu
        final ListView checkView = new ListView(this);
        checkAdapter = new GirdDropDownAdapter(this, Arrays.asList(isCheck));
        checkView.setAdapter(checkAdapter);
        checkView.setOnItemClickListener((parent, view, position, id) -> {
            binding.dropDownMenu.setTabText(isCheck[position]);
            binding.dropDownMenu.closeMenu();
            jsonObject.put("reviewState", position);
            getData();
        });

        //init state menu
        final ListView stateView = new ListView(this);
        stateAdapter = new GirdDropDownAdapter(this, Arrays.asList(checkState));
        stateView.setAdapter(stateAdapter);
        stateView.setOnItemClickListener((parent, view, position, id) -> {
            binding.dropDownMenu.setTabText(checkState[position]);
            binding.dropDownMenu.closeMenu();
            int state = position - 1;
            if (state >= 0) {
                jsonObject.put("auditState", state);
            } else {
                jsonObject.put("auditState", null);
            }
            getData();

        });

        View timeView = LayoutInflater.from(this).inflate(R.layout.layout_dropmenu_time, null);
        final TextView earliestTime = timeView.findViewById(R.id.earliest_time);
        final TextView latestTime = timeView.findViewById(R.id.latest_time);
        TextView cinfirm = timeView.findViewById(R.id.cinfirm);
        earliestTime.setOnClickListener(v -> {
            TimePickerDialog visitFloorPicker = new TimePickerDialog.Builder()
                    .setType(Type.YEAR_MONTH_DAY)
                    .setTitleStringId("最早时间")
                    .setCurrentMillseconds(System.currentTimeMillis())
                    .setThemeColor(getResources().getColor(R.color.yellow))
                    .setWheelItemTextNormalColor(getResources().getColor(R.color.colorTip))
                    .setWheelItemTextSelectorColor(getResources().getColor(R.color.colorAccent))
                    .setCallBack((timePickerView, millseconds) -> {
                        earliestTime.setText(DateUtil.getTime(millseconds, "yyyy-MM-dd"));
                        jsonObject.put("applyStartTime", DateUtil.getTime(millseconds, "yyyy-MM-dd"));
                    })
                    .build();
            visitFloorPicker.show(getSupportFragmentManager(), "year_month");
        });
        latestTime.setOnClickListener(v -> {
            TimePickerDialog visitFloorPicker = new TimePickerDialog.Builder()
                    .setType(Type.YEAR_MONTH_DAY)
                    .setTitleStringId("最晚时间")
                    .setCurrentMillseconds(System.currentTimeMillis())
                    .setThemeColor(getResources().getColor(R.color.yellow))
                    .setWheelItemTextNormalColor(getResources().getColor(R.color.colorTip))
                    .setWheelItemTextSelectorColor(getResources().getColor(R.color.colorAccent))
                    .setCallBack((timePickerView, millseconds) -> {
                        latestTime.setText(DateUtil.getTime(millseconds, "yyyy-MM-dd"));
                        jsonObject.put("applyEndTime", DateUtil.getTime(millseconds, "yyyy-MM-dd"));
                    })
                    .build();
            visitFloorPicker.show(getSupportFragmentManager(), "year_month");
        });
        cinfirm.setOnClickListener(v -> {
            binding.dropDownMenu.setTabText(earliestTime.getText() + " - " + latestTime.getText());
            binding.dropDownMenu.closeMenu();
            getData();
        });

        //init popupViews
        popupViews.add(checkView);
        popupViews.add(stateView);
        popupViews.add(timeView);

        TextView contentView = new TextView(this);
        contentView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 0));
        contentView.setGravity(Gravity.CENTER);
        //init dropdownview
        binding.dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, contentView);


        binding.recycler.setLayoutManager(new LinearLayoutManager(this));
        binding.recycler.setHasFixedSize(true);
        binding.recycler.setDivider(R.drawable.shape_divider_listview);
        binding.recycler.enableAutoLoadMore(this);
        ArrayList<Map<String, Object>> dataList = new ArrayList<>();
        adapter = new TransferAuditAdapter(dataList);
        binding.recycler.setAdapter(adapter);
        adapter.setOnItemClickListener((view, o) -> {
            Map<String, Object> map = (Map<String, Object>) o;
            Intent intent = new Intent(TransferAuditListActivity.this, DetailTransferActivity.class);
            if (Integer.parseInt(map.get("reviewState").toString()) == 0) {
                intent.putExtra("isAudit", true);
            } else {
                intent.putExtra("isAudit", false);
            }
            intent.putExtra("userbdCode", map.get("userbdCode").toString());
            startActivity(intent);
        });

        //默认加载未审核
        jsonObject.put("reviewState", 0);
        getData();
    }

    private void getData() {
        mLoadingLock = true;
        jsonObject.put("pageSize", 10);
        jsonObject.put("pageIndex", pageIndex);
        OkHttpUtils.postString()
                .url(ApiConfig.TRANSFER_AUDIT_LIST)
                .content(jsonObject.toString())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        call.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (binding.refresh.isRefreshing()) {
                            binding.refresh.setRefreshing(false);
                        }
                        if (DataFilter.filter(TransferAuditListActivity.this, response, adapter)) {
                            JSONArray data = JSON.parseArray(response.get("data").toString());
                            ArrayList<Map<String, Object>> dataList = JSON.parseObject(data.toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
                            });
                            if (pageIndex == 1) {
                                adapter.setData(dataList);
                            } else {
                                adapter.addData(dataList);
                            }
                        } else if (response.get("code").toString().equals("303")) {
                            //没有更多
                            pageIndex--;
                        }
                        if (adapter.getFooters().size() > 0)
                            adapter.removeAllFooters();
                        mLoadingLock = false;
                    }
                });

    }

    @Override
    public void loadMore() {
        if (mLoadingLock) {
            return;
        }
        pageIndex++;
        adapter.addFooter("加载中");
        getData();

    }

    @Override
    public void onRefresh() {
        pageIndex = 1;
        getData();
    }
}
